<template>
  <div class="personDialog">
    <el-dialog
      :close-on-click-modal="false"
      :model-value="visible"
      title="生产计划选择"
      width="1000px"
      draggable
      destroy-on-close
      align-center
      @close="closeDialog"
    >
      <el-row :gutter="20">
        <!-- 用户列表 -->
        <el-col :span="24">
          <div>
            <el-form
              ref="queryFormRef"
              :model="queryParams.data"
              :inline="true"
              label-width="70"
              label-position="left"
              class="dialogSeach"
            >
              <el-form-item label="工厂">
                <el-select
                  @keyup.enter="beforeSearch"
                  v-model="queryParams.data.plantId"
                  placeholder="请选择工厂"
                  clearable
                  disabled
                  @change="selectPlant"
                >
                  <el-option
                    v-for="item in plantList"
                    :key="item.id"
                    :label="item.organizationCode"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="工作中心">
                <el-select
                  @keyup.enter="search"
                  v-model="searchParam.workCenterId"
                  placeholder="请选择工作中心"
                  clearable
                >
                  <el-option
                    v-for="item in workShopList"
                    :key="item.id"
                    :label="`${item.workshopCode}-${item.workshopName}`"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item> -->
              <el-form-item label="工作年份">
                <el-select
                  @keyup.enter="beforeSearch"
                  v-model="queryParams.data.planYear"
                  placeholder="请选择工作年份"
                  clearable
                  @change="selectYear"
                >
                  <el-option
                    v-for="item in yearOptions"
                    :key="item"
                    :value="item"
                    :label="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="工作周">
                <el-select
                  @keyup.enter="beforeSearch"
                  v-model="queryParams.data.planWeek"
                  placeholder="请选择工作周"
                  clearable
                  @change="selectMonth"
                >
                  <el-option
                    v-for="item in monthOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item class="ml-[5px]">
                <el-button type="primary" @click="beforeSearch"
                  ><i-ep-search />搜索</el-button
                >
                <el-button @click="reset"> <i-ep-refresh />重置 </el-button>
              </el-form-item>
            </el-form>
          </div>
          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableData"
            row-key="id"
            @select="handleSelectionChange"
            @select-all="handleAllChange"
            height="420px"
            border
          >
            <el-table-column
              type="selection"
              width="50"
              align="center"
              :selectable="checkSelectable"
            />
            <el-table-column
              label="物料号//工序-人数-版本号"
              prop="materialId"
              show-overflow-tooltip
              align="center"
              fixed
            >
              <template #default="{ row }">
                <span>{{ `${row.descriptionCode}-${row.versionNo}` }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="卷料"
              prop="requestPlanList"
              align="center"
              show-overflow-tooltip
            >
              <template #default="{ $index, row }">
                <span>{{
                  row.requestPlanList?.length > 0 ? gross(row) : ""
                }}</span>
              </template>
            </el-table-column> -->
            <el-table-column
              label="物料号"
              prop="materialCode"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              label="计划数量"
              prop="planQuantity"
              width="120"
              align="right"
              show-overflow-tooltip
            />
            <el-table-column
              label="生产批次"
              prop="planBatch"
              width="150"
              align="center"
              show-overflow-tooltip
            />
          </el-table>
          <el-pagination
            :background="true"
            :current-page="queryParams.current"
            :page-size="queryParams.size"
            :page-sizes="[10, 25, 50, 100]"
            :total="queryTotal"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElTable } from "element-plus";
import request from "@/utils/request";
import { getPlantList, getMonthList, getYearList } from "@/utils/commonData";
import { getWeekNumber } from "@/utils/dateUtils";

defineOptions({
  name: "SelectMaterialPlanDialog",
  inheritAttrs: false,
});

interface SelectOption {
  id?: string;
}
const emit = defineEmits(["update:visible", "echo-info"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Array,
    default: () => {
      return [];
    },
  },
  isMultiple: {
    type: Boolean,
    default: true,
  },
  allocationId: {
    type: String,
    default: "",
  },
  plantId: {
    type: String,
    default: "",
  },
  searchedParams: {
    type: Object,
    default: () => {
      return {};
    },
  },
  rowIndex: {
    type: [String, Number],
    default: "",
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  selectedIds: {
    type: Array,
    default: () => [],
  },
});

const {
  visible,
  isMultiple,
  plantId,
  rowIndex,
  readonly,
  selectedIds,
  searchedParams,
} = toRefs(props);

const tableData = ref([]);
// 获取周列表
const monthOptions = ref<OptionType[]>();

// 获取年度列表
const yearOptions = ref();

// 年度变更重新获取月份
function selectYear(e: number) {
  if (e) {
    queryParams.data.planYear = e;
    queryParams.data.planWeek = "";
    monthOptions.value = getMonthList(e);
  } else {
    monthOptions.value = [];
    queryParams.data.planWeek = "";
  }
}

function selectMonth(e: number) {
  queryParams.data.planWeek = e ? e : "";
}

// 工厂编号列表
const plantList: any = ref([]);

async function selectPlant(e: string) {}

const gross = (row: any) => {
  const grossProfit: any = [];
  row.requestPlanList.forEach((item: any) => {
    grossProfit.push(`${item.materialBarcode}`);
  });
  return grossProfit.join(",");
};

const checkSelectable = (row: any) => {
  // console.log("selectedIds.value", selectedIds.value);
  if (readonly.value === true) {
    return false;
  } else {
    // if (selectedIds.value.indexOf(row.id) !== -1) {
    //   return false;
    // } else {
    //   return true;
    // }
    return true;
  }
};

function reset() {
  queryParams.current = 1;
  queryParams.size = 10;
  queryParams.data.planYear = "";
  queryParams.data.planWeek = "";
  search();
}

// 深层拷贝
function deepCopy(val: any) {
  return JSON.parse(JSON.stringify(val));
}

// 表格选择
const totalMultipleSelection: any = ref([]);
// 表格触发全选
function handleAllChange(selecteds: any) {
  if (isMultiple.value) {
    const currentSelection = deepCopy(totalMultipleSelection.value);
    const ids = deepCopy(totalMultipleIds.value);
    if (selecteds.length) {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.id);
        if (indexId < 0) {
          totalMultipleSelection.value.push(item);
        }
      });
    } else {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.id);
        if (indexId > -1) {
          currentSelection.splice(indexId, 1);
          ids.splice(indexId, 1);
        }
      });
      totalMultipleSelection.value = currentSelection;
    }
  } else {
    delAll();
    ElMessage.warning("单选，请重新选择");
  }
}
// 表格触发单个选择
function handleSelectionChange(val: any, row: SelectOption) {
  let addOptions = false;
  val?.map((item: SelectOption) => {
    if (item?.id === row?.id) {
      addOptions = true;
    }
  });
  if (!addOptions) {
    const index = totalMultipleIds.value.indexOf(row.id);
    totalMultipleSelection.value.splice(index, 1);
  } else {
    if (isMultiple.value) {
      totalMultipleSelection.value.push(row);
    } else {
      delAll();
      multipleTable.value.toggleRowSelection(row, true);
      totalMultipleSelection.value = [row];
    }
  }
}

// 右侧人员选择操作
const multipleTable = ref(ElTable);
// 全部清除
function delAll() {
  totalMultipleSelection.value = [];
  multipleTable.value.clearSelection();
}
// 单个删除
function delSingle(current: SelectOption, index: number) {
  totalMultipleSelection.value.splice(index, 1);
  tableData.value.map((item: SelectOption) => {
    if (item.id === current.id) {
      multipleTable.value.toggleRowSelection(item, false);
    }
  });
}

/** 弹窗展开 初始化数据 */
const totalMultipleIds: any = ref([]);
watch(
  () => totalMultipleSelection,
  async (newVal: any) => {
    const ids: any = [];
    newVal.value?.map((item: SelectOption) => {
      ids.push(item.id);
    });
    totalMultipleIds.value = ids;
  },
  { deep: true }
);

// 请求参数
const requestApi = "/mes/mesproduceplan/queryAvailableList";

const currentYear = new Date().getFullYear(); // 当前年份
const currentWeek = getWeekNumber(new Date()); // 当前第几周

const queryParams: any = reactive({
  current: 1,
  size: 10,
  data: {
    planWeek: "",
    planYear: "",
    plantId: "",
  },
});

// 数据请求错误后处理
function dataCallBack(data: any) {
  setTimeout(() => {
    data.map((item: SelectOption) => {
      if (totalMultipleIds.value.includes(item.id)) {
        multipleTable.value.toggleRowSelection(item, true);
      }
    });
  }, 0);
  return data;
}
onMounted(async () => {});

const beforeSearch = () => {
  if (!queryParams.data.plantId) {
    ElMessage.error("请选择工厂");
    return;
  } else {
    // console.log("queryParams.data", queryParams);
    search();
  }
};
/** 弹窗展开 初始化数据 */
const oldTotalSelection: any = ref([]);
watch(
  () => props.visible,
  async (newVal: boolean) => {
    if (newVal) {
      // 获取工厂列表
      plantList.value = await getPlantList();
      // 获取年列表
      yearOptions.value = await getYearList();
      // 获取周搜索列表
      queryParams.data.plantId = plantId.value;
      totalMultipleSelection.value = deepCopy(props.data);
      oldTotalSelection.value = deepCopy(props.data);
      dataCallBack(tableData.value);
      search();
    } else {
      tableData.value = [];
      reset();
    }
  }
);

const queryTotal = ref(0);
const loading = ref(false);

async function search() {
  const { workCenterId, planYear, planWeek } = searchedParams.value;
  queryParams.data.orderWorkCenterId = workCenterId;
  queryParams.data.orderPlanYear = planYear;
  queryParams.data.orderPlanWeek = planWeek;
  // queryParams.data.workCenterId = props.workCenterId;
  loading.value = true;
  const data: any = await request({
    url: requestApi,
    method: "post",
    data: toRaw(queryParams),
  }).finally(() => {
    loading.value = false;
  });
  queryParams.current = data.page;
  queryParams.size = data.size;
  queryTotal.value = data.total;
  tableData.value = data.data;
  dataCallBack(tableData.value);
}

const handleSizeChange = (val: number) => {
  queryParams.current = 1;
  queryParams.size = val;
  search();
};

const handleCurrentChange = (val: number) => {
  queryParams.current = val;
  search();
};

/** 关闭表单弹窗 */
function closeDialog() {
  totalMultipleSelection.value = oldTotalSelection.value;
  dataCallBack(tableData.value);
  emit("update:visible", false);
}

/** 确定提交 */
async function handleSubmit() {
  if (!isMultiple.value && totalMultipleSelection.value.length > 1) {
    ElMessage.error("请选择一个");
  } else {
    emit("update:visible", false);
    emit("echo-info", totalMultipleSelection.value, rowIndex.value);
  }
}
// 组件销毁时调用
onBeforeUnmount(() => {
  emit("update:visible", false);
  closeDialog();
});
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
